//
//  YWSelfInfoViewController.m
//  maintain
//
//  Created by Kyo on 15/11/24.
//  Copyright © 2015年 ewin. All rights reserved.
//

#import "YWSelfInfoViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"

#import "MBProgressHUD.h"
#import "YWConst.h"
#import "YWCommonTool.h"
#import "YWResourceManager.h"
#import "UIImage+ProportionalFill.h"
#import "DJWActionSheet.h"
#import "UIImageView+WebCache.h"
#import "YYPhotoGroupView.h"

#import "YWNotifyManager.h"
#import "YWPicture.h"
#import "WMHttpTool.h"
#import "YWDBTool.h"
#import "YWPushManager.h"
#import "YWLoginViewController.h"
#import "YWResetPasswordViewController.h"
#import "YWEwinManager.h"
#import "YWWorkReminderManager.h"

@interface YWSelfInfoViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) NSArray* dataArray;
@property (nonatomic, strong) UIImageView *headImageView;
@property (nonatomic, weak) MBProgressHUD* HUD;
@property (nonatomic, strong)YWPicture *avatarPicture;
@end

@implementation YWSelfInfoViewController
- (instancetype)init
{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.view.userInteractionEnabled = NO;
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.navigationController.view.userInteractionEnabled = YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = NSLocalizedString(@"personalInfo", nil);
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    _avatarPicture = [[YWPicture alloc]init];
}

- (NSArray*)dataArray
{
    if (!_dataArray) {
        NSString *headIcon = NSLocalizedString(@"headIcon", nil);
        NSString *account = NSLocalizedString(@"account", nil);
        NSString *name = NSLocalizedString(@"name", nil);
        NSString *passWord = NSLocalizedString(@"passWord", nil);
        NSString *exit = NSLocalizedString(@"exit", nil);
        NSArray* dataArray = @[@[ headIcon, account, name, passWord ],@[exit]];
        _dataArray = dataArray;
    }
    return _dataArray;
}

-(UIImageView *)headImageView{
    if (!_headImageView) {
        UIImageView* imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 54, 54)];
        YWLoginUser* loginUser = [YWLoginTool loginUser];
        NSString* urlStr = [NSString stringWithFormat:@"%@%@", kAliyunImageUrl, loginUser.headIcon];
        [imageV sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"profile_headimage"]];
        
        [imageV addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headImageViewTap:)]];
        imageV.userInteractionEnabled = YES;
        imageV.contentMode = UIViewContentModeScaleAspectFill;
        imageV.clipsToBounds = YES;
        imageV.layer.cornerRadius = 5.0;
        _headImageView = imageV;
    }
    return _headImageView;
}
- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:self.view];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextHeadPhotoUploading, nil);
        hud.dimBackground = YES;
        // hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.view addSubview:hud];
    }
    return _HUD;
}

#pragma mark - tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataArray[section] count];
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    static NSString* identifier = @"YWSelfInfoViewControllerCell";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;
        cell.textLabel.font = KTitleFont;
        cell.detailTextLabel.font = KTitleFont;
    }
    cell.textLabel.text = self.dataArray[indexPath.section][indexPath.row];
    if (indexPath.section==0) {
        YWLoginUser* loginUser = [YWLoginTool loginUser];
        if (indexPath.row == 0) {
            cell.accessoryView = self.headImageView;
        }
        else {
            cell.accessoryType = (indexPath.row == 3 ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone);
            if (indexPath.row == 1) {
                cell.detailTextLabel.text = loginUser.userAccount ?: NSLocalizedString(@"noContent", nil);
            }
            else if (indexPath.row == 2) {
                cell.detailTextLabel.text = loginUser.userName ?: NSLocalizedString(@"noContent", nil);
            }
        }
    }else{
        cell.detailTextLabel.text = nil;
        cell.accessoryView = nil;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    

    return cell;
}

#pragma mark - UITableViewDataDelegate mothods
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (indexPath.section==0 && indexPath.row == 0) {
        return 70;
    }
    return 44;
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    return 15;
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section==0) {
        if (indexPath.row == 0) {
            [DJWActionSheet showInView:self.navigationController.view
                             withTitle:NSLocalizedString(@"changeHeadIcon", nil)
                     cancelButtonTitle:NSLocalizedString(@"cancel", nil)
                destructiveButtonTitle:nil
                     otherButtonTitles:@[ NSLocalizedString(@"takePhoto", nil), NSLocalizedString(@"selectPhotoFromAlbum", nil) ]
                              tapBlock:^(DJWActionSheet* actionSheet, NSInteger tappedButtonIndex) {
                                  if (tappedButtonIndex != actionSheet.cancelButtonIndex) {
                                      UIImagePickerController* picker = [[UIImagePickerController alloc] init];
                                      picker.allowsEditing = YES;
                                      picker.delegate = self;
                                      
                                      if (tappedButtonIndex == 0) {
                                          picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                                      }
                                      else if (tappedButtonIndex == 1) {
                                          picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                                      }
                                      [self presentViewController:picker animated:YES completion:nil];
                                  }
                              }];
        }
        if (indexPath.row == 3) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"verifyLoginPassWord", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
                [textField setSecureTextEntry:YES];
                textField.keyboardType = UIKeyboardTypeASCIICapable;
                textField.clearButtonMode = UITextFieldViewModeWhileEditing;
                textField.placeholder = NSLocalizedString(@"enterPassWord", nil);
            }];
            [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
            [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                UITextField *textField = alert.textFields.firstObject;
                NSString *passWord = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                YWLoginUser* loginUser = [YWLoginTool loginUser];
                [textField resignFirstResponder];
                if ([passWord isEqualToString:loginUser.userPwd]) {
                    YWResetPasswordViewController* rpvc = [[YWResetPasswordViewController alloc] init];
                    [self.navigationController pushViewController:rpvc animated:YES];
                }else {
                    [YWCommonTool showTextHUDWithContent:passWord.length ? NSLocalizedString(@"passWordIsWrong", nil) : NSLocalizedString(@"passWordIsEmpty", nil)];
                }
            }]];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }else{
        [DJWActionSheet showInView:self.navigationController.view
                         withTitle:NSLocalizedString(@"makeSureLogout", nil)
                 cancelButtonTitle:NSLocalizedString(@"cancel", nil)
            destructiveButtonTitle:NSLocalizedString(@"logout", nil)
                 otherButtonTitles:nil
                          tapBlock:^(DJWActionSheet* actionSheet, NSInteger tappedButtonIndex) {
                              if (tappedButtonIndex == actionSheet.destructiveButtonIndex) {
                                  [self handleWithLogoutEvent];
                              }
                          }];
    }
}

#pragma mark - Common methods
- (void)handleWithLogoutEvent{
    //退出时检查是否有离线的任务
    BOOL isExist = [[YWWorkReminderManager shareManager] existUploadFailedMissions];
    if (isExist) {
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"pleaseNotice", nil) message:NSLocalizedString(@"hasUploadFailedRecordsWhenLogout", nil) preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self requestLogout];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        [self requestLogout];
    }
}

- (void)requestLogout{
    if ([[WMHttpTool shareHttpTool] existenceNetwork]) {
        [self.HUD show:YES];
        [YWLoginTool saveLoginofStatus:NO];
        
        [[WMHttpTool shareHttpTool] cancelAllRequest];
        [[YWDBTool shareDBTool] closeDatabase];
        
        [[YWPushManager shareManager] removeAllUMengAliasAndTags];
        NSString* token = [[YWPushManager shareManager] deviceToken];
        [[YWEwinManager shareManager] requestLogoutWithDeviceToken:token WithComplete:^(NSInteger statusCode) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.HUD hide:YES];
                if (statusCode == 200) {
                    [[UIApplication sharedApplication] setStatusBarHidden:NO];
                    UIWindow* window = [UIApplication sharedApplication].keyWindow;
                    window.rootViewController = [[YWLoginViewController alloc] init];
                }else{
                    [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"logoutFailed", nil)];
                }
            });
        }];
    }else {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
    }
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
    //    UIImage *image=[info objectForKey:UIImagePickerControllerEditedImage];

    [self.HUD show:YES];
    [picker dismissViewControllerAnimated:YES completion:^{
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            UIImage* photoImage = [info objectForKey:UIImagePickerControllerEditedImage];
            if (!photoImage) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.HUD hide:YES];
                    [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextErrorOfGetImage, nil)];
                });
                return;
            }
            NSString* bigImageName = [NSString stringWithFormat:@"%@.png", [YWCommonTool randStringId]];
            NSString* smallImageName = [[YWResourceManager shareManager] smallPictureName:bigImageName];
            @autoreleasepool{
                CGFloat width = photoImage.size.width;
                CGFloat heigth = photoImage.size.height;
                CGFloat bigSize = 960.0f;
                CGFloat smallSize = 200.0f;
                UIImage* bigImage = photoImage;
                UIImage* smallImage = photoImage;
                if (width > heigth) {
                    if (width > bigSize) {
                        bigImage = [photoImage scaleToSize:CGSizeMake(bigSize * width / heigth, bigSize)];
                    }
                    if (width > smallSize) {
                        smallImage = [photoImage scaleToSize:CGSizeMake(smallSize * width / heigth, smallSize)];
                    }
                }else {
                    if (heigth > bigSize) {
                        bigImage = [photoImage scaleToSize:CGSizeMake(bigSize, bigSize * heigth / width)];
                    }
                    if (heigth > smallSize) {
                        smallImage = [photoImage scaleToSize:CGSizeMake(smallSize, smallSize * heigth / width)];
                    }
                }
                //保存本地
                NSData* bigImageData = UIImageJPEGRepresentation(bigImage, 0.1);
                NSData* smallImageData = UIImageJPEGRepresentation(smallImage, 0.3);
                [[YWResourceManager shareManager] saveDataToCacheStorage:bigImageData withResourcePath:bigImageName];
                [[YWResourceManager shareManager] saveDataToCacheStorage:smallImageData withResourcePath:smallImageName];
            }
            _avatarPicture.uploadStatus =  YWPictureUploadStatusNull;
            _avatarPicture.pictureName = bigImageName;
            if ([[WMHttpTool shareHttpTool] existenceNetwork]) {
                [[YWResourceManager shareManager] uploadLocalPictureToAliyunOSS:_avatarPicture?@[_avatarPicture]:nil isAvatar:YES complete:^(BOOL isError, NSArray *uploadPictures) {
                    if (isError) {
                        [self.HUD hide:YES];
                        if (![[WMHttpTool shareHttpTool]existenceNetwork]) {
                            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
                        }else{
                            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"uploadFailed", nil)];
                            [[YWResourceManager shareManager] deleteDataWithImageName:bigImageName];
                            [[YWResourceManager shareManager] deleteDataWithImageName:smallImageName];
                        }
                    }else{
                        [self modifySelfAvatarWith:uploadPictures error:isError];
                    }
                }];
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.HUD hide:YES];
                    [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoNetwork, nil)];
                    [self deleteLocalPictureData];
                });
            }
        });
    }];
}

- (void)modifySelfAvatarWith:(NSArray*)avatar error:(BOOL)isError{
    if (avatar.count>0) {
        NSDictionary *headersDic = [YWCommonTool addSubHttpHeadWithDic:[WMHttpTool shareHttpTool].HTTPHeaders];
        [WMHttpTool shareHttpTool].HTTPHeaders = headersDic;
        if (headersDic == nil) {return;}
        
        YWPicture *picture = (YWPicture *)avatar[0];
        NSDictionary* params = @{ @"headIcon" : picture.smallPictureUrl?:@""};
        
        [[WMHttpTool shareHttpTool] putWithUrl:[YWCommonTool modifySelfInfoUrl] params:params success:^(NSHTTPURLResponse* response, id json) {
            dispatch_async(dispatch_get_main_queue(), ^{
                YWLoginUser* loginUser = [YWLoginTool loginUser];
                loginUser.headIcon = picture.smallPictureUrl;
                [YWLoginTool saveLoginOfUser:loginUser];
                [self.HUD hide:YES];
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"uploadSucceed", nil)];
                NSString* urlStr = [NSString stringWithFormat:@"%@%@", kAliyunImageUrl, loginUser.headIcon];
                [self.headImageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"profile_headimage"]];
                [[YWNotifyManager shareManager] postModifySelfHeadIconNotify];
            });
        } failure:^(NSHTTPURLResponse* response, NSError* error) {
            [self.HUD hide:YES];
            YWLog(@"%s,error:%@", __func__, error.localizedDescription);
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"uploadFailed", nil)];
        }];
        [self deleteLocalPictureData];
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.HUD hide:YES];
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextErrorOfGetImage, nil)];
        });
    }
}

- (void)deleteLocalPictureData{
    //删除本地图片
    NSString* smallImageName = [[YWResourceManager shareManager] smallPictureName:_avatarPicture.pictureName];
    [[YWResourceManager shareManager] deleteDataWithImageName:_avatarPicture.pictureName];
    [[YWResourceManager shareManager] deleteDataWithImageName:smallImageName];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController*)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    //picker = nil;
}

-(void)headImageViewTap:(id)sender{
    YWLoginUser* loginUser = [YWLoginTool loginUser];
    YYPhotoGroupItem *item = [YYPhotoGroupItem new];
    item.thumbView = _headImageView;
    if (loginUser.headIcon.length>0) {
        //去掉preview_就是大图的url
        NSString *bigUrl = [loginUser.headIcon stringByReplacingOccurrencesOfString:kBigPictureNamePrefix withString:@""];
        NSString* urlStr = [NSString stringWithFormat:@"%@%@", kAliyunImageUrl, bigUrl];
        item.largeImageURL = [NSURL URLWithString:urlStr];
    }else{
        item.largeImageURL = nil;
    }
    
    UIView *fromView = _headImageView;
    
    YYPhotoGroupView *v = [[YYPhotoGroupView alloc] initWithGroupItems:@[item]];
    [v presentFromImageView:fromView toContainer:[UIApplication sharedApplication].keyWindow animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
